import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/chat_model.dart';
import '../../core/providers/team_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class GroupChatScreen extends ConsumerStatefulWidget {
  final String teamId;
  final String chatGroupId;

  const GroupChatScreen({
    super.key,
    required this.teamId,
    required this.chatGroupId,
  });

  @override
  ConsumerState<GroupChatScreen> createState() => _GroupChatScreenState();
}

class _GroupChatScreenState extends ConsumerState<GroupChatScreen> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);
    final chatGroup = ref
        .read(teamProvider.notifier)
        .getChatGroup(widget.chatGroupId);
    final messagesAsync = ref.watch(chatMessagesProvider(widget.chatGroupId));

    if (currentUser == null || chatGroup == null) {
      return Scaffold(
        body: Center(
          child: Text('Loading...').fontSize(16.sp).textColor(Colors.grey),
        ),
      );
    }

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child:
              [
                _buildTopNavigationBar(),
                _buildMemberAvatarList(chatGroup),
                Expanded(
                  child: messagesAsync.when(
                    data:
                        (messages) =>
                            _buildMessageList(messages, currentUser.id),
                    loading:
                        () => Center(
                          child: CircularProgressIndicator(
                            color: Color(0xFFFFD700),
                          ),
                        ),
                    error:
                        (error, stack) => Center(
                          child: Text(
                            'Error loading messages',
                          ).fontSize(16.sp).textColor(Colors.grey),
                        ),
                  ),
                ),
                _buildBottomInputArea(currentUser),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child:
          [
            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Colors.black,
                shape: BoxShape.circle,
              ),
              child:
                  Icon(
                    Icons.arrow_back_ios_new,
                  ).iconSize(16.sp).iconColor(Colors.white).center(),
            ).inkWell(onTap: () => GoRouter.of(context).pop()),

            Spacer(),

            Text(
              'Group Chat',
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black,
                fontFamily: 'PoetsenOne',
              ),
            ),

            Spacer(),

            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Colors.black,
                shape: BoxShape.circle,
              ),
              child:
                  Icon(
                    AliIcons.iconReport,
                  ).iconSize(22.sp).iconColor(Colors.white).center(),
            ).inkWell(onTap: _showReportDialog),
          ].toRow(),
    );
  }

  Widget _buildMemberAvatarList(ChatGroupEntity chatGroup) {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final members =
        allUsers
            .where((user) => chatGroup.memberIds.contains(user.id))
            .toList();
    final currentUser = ref.watch(currentUserProvider);

    return Container(
      height: 80.h,
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child:
            [
              for (final member in members)
                Container(
                  margin: EdgeInsets.only(right: 12.w),
                  child: Container(
                    width: 60.w,
                    height: 60.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      image: DecorationImage(
                        image: AssetImage(member.avatar),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ).inkWell(
                    onTap: () {
                      if (currentUser != null && member.id == currentUser.id) {
                        return;
                      }
                      GoRouter.of(
                        context,
                      ).push('/other-user-profile/${member.id}');
                    },
                  ),
                ),
            ].toRow(),
      ),
    );
  }

  Widget _buildMessageList(
    List<ChatMessageEntity> messages,
    String currentUserId,
  ) {
    return ListView.builder(
      controller: _scrollController,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      itemCount: messages.length,
      itemBuilder: (context, index) {
        final message = messages[index];
        final isCurrentUser = message.senderId == currentUserId;
        return _buildMessageItem(message, isCurrentUser);
      },
    );
  }

  Widget _buildMessageItem(ChatMessageEntity message, bool isCurrentUser) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: [
        if (!isCurrentUser) ...[
          Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.black,
            ),
            padding: EdgeInsets.only(right: 2.w, bottom: 2.w),
            child: Container(
              width: 52.w,
              height: 52.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image: AssetImage(message.senderAvatar),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: [
              if (message.messageType == MessageType.text)
                _buildTextMessage(message.content, isCurrentUser)
              else if (message.messageType == MessageType.image)
                _buildImageMessage(message.content, isCurrentUser),
            ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
          ),
          SizedBox(width: 40.w),
        ] else ...[
          SizedBox(width: 40.w),
          Expanded(
            child: [
              if (message.messageType == MessageType.text)
                _buildTextMessage(message.content, isCurrentUser)
              else if (message.messageType == MessageType.image)
                _buildImageMessage(message.content, isCurrentUser),
            ].toColumn(crossAxisAlignment: CrossAxisAlignment.end),
          ),
          SizedBox(width: 12.w),
          Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.black,
            ),
            padding: EdgeInsets.only(right: 2.w, bottom: 2.w),
            child: Container(
              width: 52.w,
              height: 52.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image: AssetImage(message.senderAvatar),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
        ],
      ].toRow(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  Widget _buildTextMessage(String content, bool isCurrentUser) {
    return Container(
      padding:
          isCurrentUser
              ? EdgeInsets.only(left: 1.w, bottom: 1.w)
              : EdgeInsets.only(right: 1.w, bottom: 1.w),
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(29.r),
      ),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        decoration: BoxDecoration(
          color: Color(0xFFFDF5E1),
          borderRadius: BorderRadius.circular(29.r),
          border: Border.all(color: Colors.black, width: 2.w),
        ),
        child: Text(
          content,
          style: TextStyle(fontSize: 14.sp, color: Colors.black),
        ),
      ),
    );
  }

  Widget _buildImageMessage(String imagePath, bool isCurrentUser) {
    return Container(
      width: 155.w,
      height: 155.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(color: Colors.black, width: 2.w),
        image: DecorationImage(image: AssetImage(imagePath), fit: BoxFit.cover),
      ),
    );
  }

  Widget _buildBottomInputArea(dynamic currentUser) {
    return Container(
      margin: EdgeInsets.all(16.w),
      padding: EdgeInsets.only(right: 2.w, bottom: 2.w),
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(28.r),
      ),
      child: Container(
        decoration: BoxDecoration(
          color: Color(0xFFF5F5DC),
          borderRadius: BorderRadius.circular(28.r),
          border: Border.all(color: Colors.black, width: 1.w),
        ),
        child: SafeArea(
          top: false,
          child: Container(
            height: 56.h,
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child:
                [
                  Expanded(
                    child: TextField(
                      controller: _messageController,
                      decoration: InputDecoration(
                        hintText: 'say something...',
                        hintStyle: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 16.sp,
                        ),
                        border: InputBorder.none,
                        isDense: true,
                      ),
                      style: TextStyle(fontSize: 16.sp, color: Colors.black),
                      maxLines: null,
                      textInputAction: TextInputAction.done,
                      onChanged: (value) {
                        setState(() {});
                      },
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Container(
                    width: 40.w,
                    height: 40.w,
                    decoration: BoxDecoration(
                      color: Color(0xFFFFD700),
                      shape: BoxShape.circle,
                    ),
                    child:
                        Icon(
                          AliIcons.iconPhoto,
                        ).iconSize(22.sp).iconColor(Colors.white).center(),
                  ).inkWell(onTap: () => _selectImage(currentUser)),
                  SizedBox(width: 8.w),
                  Container(
                    width: 40.w,
                    height: 40.w,
                    decoration: BoxDecoration(
                      color: Color(0xFFFFD700),
                      shape: BoxShape.circle,
                    ),
                    child:
                        Icon(
                          AliIcons.iconSend,
                        ).iconSize(22.sp).iconColor(Colors.white).center(),
                  ).inkWell(
                    onTap:
                        _messageController.text.trim().isNotEmpty
                            ? () => _sendTextMessage(currentUser)
                            : null,
                  ),
                ].toRow(),
          ),
        ),
      ),
    );
  }

  void _showReportDialog() {
    PopupHelper.showReportDialog(
      context,
      onReportSubmitted: (reportType) async {
        if (mounted) {
          final success = await ref
              .read(teamProvider.notifier)
              .deleteChatMessages(widget.chatGroupId);

          if (success) {
            if (mounted) {
              ToastHelper.success(
                'Report submitted successfully',
                context: context,
              );
              GoRouter.of(context).pop();
            }
          } else {
            if (mounted) {
              ToastHelper.error('Failed to clear chat', context: context);
            }
          }
        }
      },
      onCancelPressed: () {},
    );
  }

  Future<void> _selectImage(dynamic currentUser) async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          themeColor: Color(0xFFFFD700),
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final file = await assets.first.file;
        if (file != null) {
          await _sendImageMessage(currentUser, file.path);
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to select image', context: context);
      }
    }
  }

  Future<void> _sendTextMessage(dynamic currentUser) async {
    final content = _messageController.text.trim();
    if (content.isEmpty) return;

    final success = await ref
        .read(teamProvider.notifier)
        .sendMessage(
          chatGroupId: widget.chatGroupId,
          senderId: currentUser.id,
          senderName: currentUser.username,
          senderAvatar: currentUser.avatar,
          messageType: MessageType.text,
          content: content,
        );

    if (success) {
      _messageController.clear();
      _scrollToBottom();
    } else {
      if (mounted) {
        ToastHelper.error('Failed to send message', context: context);
      }
    }
  }

  Future<void> _sendImageMessage(dynamic currentUser, String imagePath) async {
    final success = await ref
        .read(teamProvider.notifier)
        .sendMessage(
          chatGroupId: widget.chatGroupId,
          senderId: currentUser.id,
          senderName: currentUser.username,
          senderAvatar: currentUser.avatar,
          messageType: MessageType.image,
          content: imagePath,
        );

    if (success) {
      _scrollToBottom();
      if (mounted) {
        ToastHelper.success('Image sent', context: context);
      }
    } else {
      if (mounted) {
        ToastHelper.error('Failed to send image', context: context);
      }
    }
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }
}
